package com.peaker.advertisingpro.utils

import android.content.Context
import android.os.Environment
import android.util.Log
import java.io.*
import java.text.SimpleDateFormat
import java.util.*

object LogToFile {

    private const val TAG = "LogToFile"

    private var logPath: String? = null //log日志存放路径


    private val dateFormat: SimpleDateFormat = SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.US) //日期格式;
    private val dateFormat1: SimpleDateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.US) //日期格式;


    private val date: Date = Date() //因为log日志是使用日期命名的，使用静态成员变量主要是为了在整个程序运行期间只存在一个.log文件中;


    /**
     * 初始化，须在使用之前设置，最好在Application创建时调用
     *
     * @param context
     */
    fun init(context: Context) {
        logPath = getFilePath(context) + "/Logs" //获得文件储存路径,在后面加"/Logs"建立子文件夹
    }

    /**
     * 获得文件存储路径
     *
     * @return
     */
    private fun getFilePath(context: Context): String {
        return if (Environment.MEDIA_MOUNTED.equals(Environment.MEDIA_MOUNTED) || !Environment.isExternalStorageRemovable()) { //如果外部储存可用
            Environment.getExternalStoragePublicDirectory("MIPS2").path

        } else {
            context.filesDir.path //直接存在/data/data里，非root手机是看不到的
        }
    }

    private const val VERBOSE = 'v'

    private const val DEBUG = 'd'

    private const val INFO = 'i'

    private const val WARN = 'w'

    private const val ERROR = 'e'

    fun v(tag: String, msg: String) {
        writeToFile(VERBOSE, tag, msg)
    }

    fun d(tag: String, msg: String) {
        writeToFile(DEBUG, tag, msg)
    }

    fun i(tag: String, msg: String) {
        writeToFile(INFO, tag, msg)
    }

    fun w(tag: String, msg: String) {
        writeToFile(WARN, tag, msg)
    }

    fun e(tag: String, msg: String) {
        writeToFile(ERROR, tag, msg)
    }

    /**
     * 将log信息写入文件中
     *
     * @param type
     * @param tag
     * @param msg
     */
    private fun writeToFile(type: Char, tag: String, msg: String) {
        if (null == logPath) {
            Log.e(TAG, "logPath == null ，未初始化LogToFile")
            return
        }
        val fileName = logPath + "/log_" + dateFormat1.format(Date()) + ".log" //log日志名，使用时间命名，保证不重复
        val log: String = dateFormat.format(date)
            .toString() + " " + type + " " + tag + " " + msg + "\n" //log日志内容，可以自行定制

        //如果父路径不存在
        val file = File(logPath)
        if (!file.exists()) {
            file.mkdirs() //创建父路径
        }
        var fos: FileOutputStream? = null //FileOutputStream会自动调用底层的close()方法，不用关闭
        var bw: BufferedWriter? = null
        try {
            fos = FileOutputStream(fileName, true) //这里的第二个参数代表追加还是覆盖，true为追加，flase为覆盖
            bw = BufferedWriter(OutputStreamWriter(fos))
            bw.write(log)
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        } catch (e: IOException) {
            e.printStackTrace()
        } finally {
            try {
                if (bw != null) {
                    bw.close() //关闭缓冲流
                }
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }
}